<template>
  <div class="config-list">
    <div class="swiper" id="swiper" v-if="moduleData.length">
      <div class="watch-list-arrow watch-list-arrow--left" @click="onPageLeft" v-if="isShowTabArrow">
        <div class="watch-list-arrow-btn">
          <svg-icon iconClass="left-arrow-icon"></svg-icon>
        </div>
      </div>
      <div ref="currencyItemsRef" class="currency-items" id="tabsContainer">
        <div
          class="currency-item"
          :class="{ 'active-item': activeIndex === index }"
          v-for="(item, index) in moduleData"
          :key="item.modelId"
          @click="handelTabItem(item, index)"
        >
          {{ item.modelName }}
        </div>
      </div>
      <div class="watch-list-arrow watch-list-arrow--right" @click="onPageRight" v-if="isShowTabArrow">
        <div class="watch-list-arrow-btn">
          <svg-icon iconClass="right-arrow-icon"></svg-icon>
        </div>
      </div>
    </div>
    <div class="config-list__items" v-loading="isLoadingList">
      <template v-if="configList.length">
        <div class="config-list__items-item" v-for="item in configList" :key="item.checkId">
          <div class="item-header">
            <div class="item-header-info">
              <div class="item-header-icon"></div>
              <div class="item-header-label">{{ acceptanceLabel(item) }}</div>
              <!-- <el-tag :type="item.state[0]">{{ item.state[1] }}</el-tag> -->
              <div class="status-tag" :class="`status-tag-${item.stateLabel[0]}`">{{ item.stateLabel[1] }}</div>
            </div>
            <div class="item-header-buttons">
              <template v-if="item.isOperate">
                <el-button v-if="[5, 8].includes(item.state)" type="danger" link @click="handelShowDialog(item.checkId, 'edit')"
                  >未通过，再提交</el-button
                >
                <el-button v-if="[2].includes(item.state)" type="primary" link @click="handelShowDialog(item.checkId, 'add')"
                  >去验收</el-button
                >
                <div class="divider-line" v-if="[2, 5, 8].includes(item.state)"></div>
              </template>
              <el-button v-if="item.isUpload === 1" type="primary" link @click="handelShowDialog(item.checkId, 'detail')"
                >查看</el-button
              >
              <el-button v-if="!item.isUpload" type="info" link>未上传</el-button>
            </div>
          </div>
          <div class="item-content">
            <el-form>
              <el-form-item label="标准说明：">
                {{ item.checkDesc }}
              </el-form-item>
              <el-form-item label="标准图示：" v-show="item.imageList.length">
                <image-video-upload disabled :fileList="item.imageList" />
              </el-form-item>
              <el-form-item label="标准视频：" v-show="item.videoList.length">
                <image-video-upload fileType="video" item-size="113px" disabled :fileList="item.videoList" />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>
      <el-empty v-else />
    </div>

    <el-dialog v-model="isShowDialog" title="操作" width="900" :show-close="false" @close="handelCancel">
      <el-form
        :model="form"
        :rules="{
          businessCheckDesc: { required: true, message: '请输入标准描述', trigger: 'blur' }
        }"
        label-width="auto"
        ref="formRef"
        v-if="isShowDialog"
        v-loading="isFormLoading"
      >
        <el-form-item label="验收标准" prop="businessCheckDesc">
          <el-input
            v-model="form.businessCheckDesc"
            type="textarea"
            :disabled="isFormDisabled"
            placeholder="请输入标准描述"
            :maxlength="80"
            :autosize="{ minRows: 4 }"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="工艺标准图">
          <image-video-upload
            :file-list="picData"
            :disabled="isFormDisabled"
            tip="只能上传jpg/png，且不超过10M,最大支持上传9张"
            accept=".jpg,.png"
            multiple
            :max-size="10"
            :max-length="9"
            @upload-success="uploadImage"
            @upload-remove="uploadImageRemove"
          />
        </el-form-item>
        <el-form-item label="工艺标准视频">
          <image-video-upload
            :file-list="videoData"
            :disabled="isFormDisabled"
            fileType="video"
            item-size="113px"
            accept=".avi,.mov,.mp4,.wmv"
            tip="只能上传 avi/mov/mp4/wmv 文件格式，单个不超过200MB，最大支持6个"
            multiple
            :max-size="200"
            :max-length="6"
            @upload-success="uploadVideo"
            @upload-remove="uploadVideoRemove"
          />
        </el-form-item>
      </el-form>
      <template #header>
        <div class="header-title">
          <span class="icon"></span>
          <span class="title">操作</span>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button style="width: 92px; background-color: #f2f3f5" @click="handelCancel">取消</el-button>
          <el-button style="width: 92px" type="primary" @click="handelConfirm" v-show="!isFormDisabled"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onUnmounted, getCurrentInstance, computed, watch, nextTick } from "vue";
import useWindowSize from "@/hooks/useWindowSize";
import {
  acceptanceModule,
  getAcceptanceList as acceptanceList,
  acceptancePlanInfo,
  submitAcceptancePlanInfo
} from "@/apis/clientManager";
import useUserStore from "@/store/modules/user";
import { acceptanceState } from "../config";

const props = defineProps({
  customerId: {
    type: String,
    default: ""
  }
});
const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const moduleData = ref([]);
const configList = ref([]);
const isLoadingList = ref(false);
const catchModelId = ref("");

// TODO:暂时使用该方式
const acceptanceLabel = computed(() => {
  return item => {
    const checkTypes = item?.checkType?.split(",") || [];
    if (checkTypes.length >= 2) {
      return `${item.procedureName}-【${checkTypes[0]}】【${checkTypes[1]}】 ${item.craftName}`;
    }
    return `${item.procedureName}-【${checkTypes[0]}】${item.craftName}`;
  };
});
const handelListData = (ids, urls) => {
  const idsData = ids ? ids.split(",") : [];
  const urlsData = urls ? urls.split(",") : [];
  return (
    idsData?.map((item, index) => {
      return {
        fileId: item,
        fileUrl: urlsData?.length && urlsData[index]
      };
    }) || []
  );
};
const getAcceptanceModule = async () => {
  const { data } = await acceptanceModule(props.customerId);
  moduleData.value = data || [];
  if (data?.length) {
    catchModelId.value = data[0].modelId;
    handelBindScrollEvent();
    checkIsShowArrow();
    getAcceptanceList(data[0].modelId);
  }
};
const getAcceptanceList = async modelId => {
  try {
    isLoadingList.value = true;
    const { data } = await acceptanceList(props.customerId, modelId);
    configList.value =
      data?.checkList?.map(item => {
        return {
          ...item,
          stateLabel: acceptanceState.has(item.state) ? acceptanceState.get(item.state) : ["danger", "状态错误"],
          imageList: handelListData(item?.picIds, item?.picUrls),
          videoList: handelListData(item?.videoIds, item?.videoUrls)
        };
      }) || [];
    isLoadingList.value = false;
  } catch (err) {
    isLoadingList.value = false;
  }
};

const isShowDialog = ref(false);
const isFormLoading = ref(false);
const isFormDisabled = ref(false);
const formInit = {
  businessCheckDesc: "",
  checkPicIds: "",
  checkPicUrls: "",
  checkVideoIds: "",
  checkVideoUrls: "",
  deptId: userStore.userInfo?.mainDeptId || ""
};
const itemCheckId = ref("");
const form = ref({ ...formInit });
const picData = ref([]);
const videoData = ref([]);
const uploadImage = data => {
  picData.value.push({
    ...data
  });
};
const uploadImageRemove = index => {
  picData.value.splice(index, 1);
};
const uploadVideo = data => {
  videoData.value.push({
    ...data
  });
};
const uploadVideoRemove = index => {
  videoData.value.splice(index, 1);
};
const handelDetailData = data => {
  const picIds = data?.checkPicIds ? data.checkPicIds?.split(",") : [];
  const picUrls = data?.checkPicUrls ? data.checkPicUrls?.split(",") : [];
  const videoIds = data?.checkVideoIds ? data.checkVideoIds?.split(",") : [];
  const videoUrls = data?.checkVideoUrls ? data.checkVideoUrls?.split(",") : [];
  picIds.forEach((item, index) => {
    picData.value.push({ fileId: item, fileUrl: picUrls[index], url: picUrls[index] });
  });
  videoIds.forEach((item, index) => {
    videoData.value.push({ fileId: item, fileUrl: videoUrls[index], url: videoUrls[index] });
  });
};
const getAcceptanceInfo = async checkId => {
  try {
    isFormLoading.value = true;
    picData.value = [];
    videoData.value = [];
    const { data } = await acceptancePlanInfo(checkId);
    handelDetailData(data);
    data.deptId = userStore.userInfo?.mainDeptId || "";
    form.value = data;
    isFormLoading.value = false;
  } catch (err) {
    isFormLoading.value = false;
  }
};
const handelShowDialog = (checkId, type) => {
  itemCheckId.value = checkId;
  ["edit", "detail"].includes(type) && getAcceptanceInfo(checkId);
  type === "detail" && (isFormDisabled.value = true);
  isShowDialog.value = true;
};
const handelSubmitData = () => {
  let picIds = [],
    picUrls = [],
    videoIds = [],
    videoUrls = [];
  picData.value.forEach(item => {
    picIds.push(item.fileId);
    picUrls.push(item.fileUrl);
  });
  videoData.value.forEach(item => {
    videoIds.push(item.fileId);
    videoUrls.push(item.fileUrl);
  });
  return {
    checkPicIds: picIds.join(","),
    checkPicUrls: picUrls.join(","),
    checkVideoIds: videoIds.join(","),
    checkVideoUrls: videoUrls.join(",")
  };
};
const handelCancel = () => {
  isShowDialog.value = false;
  isFormDisabled.value = false;
  picData.value = [];
  videoData.value = [];
  form.value = { ...formInit };
};
const handelConfirm = () => {
  proxy.$refs.formRef.validate(async valid => {
    if (!valid) {
      return proxy.$modal.msgError("请填写完整");
    }
    try {
      const postData = {
        ...form.value,
        ...handelSubmitData()
      };
      isFormLoading.value = true;
      await submitAcceptancePlanInfo(itemCheckId.value, postData);
      proxy.$modal.msgSuccess("保存成功");
      getAcceptanceList(catchModelId.value);
      isFormLoading.value = false;
      isShowDialog.value = false;
    } catch (err) {
      isFormLoading.value = false;
    }
  });
};

/**
 * TODO:封装tabs通用组件
 */
const activeIndex = ref(0);
const handelTabItem = (item, index) => {
  activeIndex.value = index;
  catchModelId.value = item.modelId;
  getAcceptanceList(item.modelId);
};

const currencyItemsRef = ref(null);
const isShowTabArrow = ref(false);
const { width } = useWindowSize();
watch(
  () => width.value,
  () => {
    checkIsShowArrow();
  }
);
const onPageLeft = () => {
  currencyItemsRef.value.scroll({
    left: currencyItemsRef.value.scrollLeft - currencyItemsRef.value.offsetWidth,
    behavior: "smooth"
  });
};
const onPageRight = () => {
  currencyItemsRef.value.scroll({
    left: currencyItemsRef.value.scrollLeft + currencyItemsRef.value.offsetWidth,
    behavior: "smooth"
  });
};
const handleScroll = e => {
  const direction = e.deltaY > 0 ? "0" : "1";
  const tabBar = document.getElementById("tabsContainer");
  tabBar.scrollLeft += direction === "0" ? 64 : -64;
};
const checkIsShowArrow = async () => {
  await nextTick();
  const swiperSize = document.getElementById("swiper");
  isShowTabArrow.value = swiperSize && !(swiperSize.offsetWidth / 138 > moduleData.value.length);
};
const handelBindScrollEvent = async () => {
  await nextTick();
  const tabBar = document.getElementById("tabsContainer");
  tabBar && tabBar.addEventListener("wheel", handleScroll, { passive: true });
};
const handelRemoveScrollEvent = async () => {
  await nextTick();
  const tabBar = document.getElementById("tabsContainer");
  tabBar && tabBar.removeEventListener("wheel", handleScroll);
};
onUnmounted(() => {
  handelRemoveScrollEvent();
});

getAcceptanceModule();
</script>

<style scoped lang="scss">
@use "@/assets/styles/mixin";
.config-list {
  @include mixin.flex-column;
  width: 100%;
  height: calc(100% - 80px);
  &__items {
    position: relative;
    flex: 1;
    overflow-y: auto;
    padding: 0 20px;
    box-sizing: border-box;
    &-item {
      background-color: #f5f7fa;
      border-radius: 4px;
      &:not(:first-child) {
        margin-top: 20px;
      }
    }
    :deep(.el-empty) {
      @include mixin.position-center;
    }
  }
  .item-header {
    @include mixin.flex-between;
    padding: 20px;
    box-sizing: border-box;
    border-bottom: 1px solid #dcdfe6;
    &-info {
      @include mixin.flex-align;
    }
    &-icon {
      width: 4px;
      height: 16px;
      background-color: #007dff;
      border-radius: 4px;
    }
    &-label {
      margin: 0 20px 0 8px;
      font-size: 14px;
      color: #3d3d3d;
      line-height: 24px;
    }
    &-buttons {
      @include mixin.flex-align;
      .divider-line {
        width: 2px;
        height: 15px;
        margin: 0 5px;
        background-color: #007dff;
      }
    }
  }
  .item-content {
    padding: 20px;
    box-sizing: border-box;
  }
}

.header-title {
  @include mixin.flex-align;
  .icon {
    width: 6px;
    height: 6px;
    margin-right: 8px;
    background-color: #409eff;
    border-radius: 50%;
  }
  font-size: 18px;
  color: #131414;
  line-height: 24px;
}
.dialog-footer {
  text-align: center;
  margin-top: 50px;
  :deep(.el-button) {
    width: 92px;
    height: 36px;
  }
}

.swiper {
  @include mixin.flex-align;
  overflow: hidden;
  margin-bottom: 20px;
}
.watch-list-arrow {
  @include mixin.flex-center;
  cursor: pointer;
  background-color: #f5f7fa;
  border: 0 solid #e7e7e7;
  &--left {
    border-right: 1px solid #e7e7e7;
  }
  &--right {
    border-left: 1px solid #e7e7e7;
  }
}
.watch-list-arrow-btn {
  @include mixin.flex-center;
  width: 48px;
  height: 64px;
  font-size: 10px;
}
.currency-items {
  display: flex;
  overflow-x: scroll;
  &::-webkit-scrollbar {
    display: none;
  }
}
.watch-list-arrow-btn,
.currency-item {
  border-bottom: 1px solid #e7e7e7;
}
.currency-item {
  @include mixin.flex-center;
  flex: 0 0 auto;
  width: 138px;
  height: 64px;
  border-top: 0;
  border-right: 1px solid #e7e7e7;
  background-color: #f5f7fa;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.6);
  line-height: 24px;
  cursor: pointer;
  user-select: none;
  &:last-child {
    border-right: 0;
  }
}
.active-item {
  color: #007dff;
  background-color: #fff;
}

// 状态
.status-tag {
  @include mixin.flex-inline-flex;
  height: 20px;
  padding: 0 10px;
  border-radius: 2px;
  border: 1px solid #ffffff;
  font-weight: 400;
  font-size: 12px;
  line-height: 20px;
  // 验收中
  &-info {
    background-color: #dcdfe6 !important;
    color: #606266 !important;
  }
  // 未通过 内部不通过&客户不通过
  &-danger {
    background-color: #ffc7c7 !important;
    color: #ff3333 !important;
  }
  // 审核中
  &-warning {
    background-color: #fff0d9 !important;
    color: #ff9900 !important;
  }
  // 待验收
  &-primary {
    background-color: #d9edff !important;
    color: #409eff !important;
  }
  // 已验收  内部已验收&客户已验收
  &-success {
    background-color: #d2f1de !important;
    color: #14c85c !important;
  }
}
</style>
